package com.remoter.api.context.support;

import java.net.InetSocketAddress;

import com.remoter.api.context.IModule;

public abstract class AbstractModule implements IModule{
	
	private static final long serialVersionUID = 6436699515379960363L;

	protected String server;
	protected String host;
	protected int port;
	protected String bean;
	protected String type;
	protected transient Class<?> typeClass;
	protected long starttime;
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T parseModule(Class<T> type){
		return (T)this;
	}

	@Override
	public IModule setServer(String server) {
		this.server = server;
		return this;
	}

	@Override
	public IModule setHost(String host) {
		this.host = host;
		return this;
	}

	@Override
	public IModule setPort(int port) {
		this.port = port;
		return this;
	}

	@Override
	public IModule setType(Class<?> type) {
		this.type = type.getName();
		this.typeClass = type;
		return this;
	}

	@Override
	public IModule setBean(String bean) {
		this.bean = bean;
		return this;
	}

	@Override
	public String getServer() {
		return this.server;
	}

	@Override
	public String getHost() {
		return this.host;
	}

	@Override
	public int getPort() {
		return this.port;
	}

	@Override
	public String getBean() {
		return this.bean;
	}
	
	@Override
	public String getType() {
		return this.type;
	}
	
	@Override
	public Class<?> getTypeClass() {
		return this.typeClass;
	}
	
	@Override
	public String getPath(){
		StringBuilder sb = new StringBuilder("/");
		sb.append(this.server).append("/");
		sb.append(this.type).append("(").append(this.bean).append(")").append("/");
		if(this.isImporter()){
			sb.append("consumers/");
		}else{
			sb.append("providers/");
		}
		sb.append(this.host).append(":").append(this.port);
		return sb.toString();
	}
	
	@Override
	public String getServiceKey(){
		StringBuilder sb = new StringBuilder("/");
		sb.append(this.server).append("/");
		sb.append(this.type).append("(").append(this.bean).append(")");
		return sb.toString();
	}
	
	@Override
	public InetSocketAddress getSocketAddress() {
		return new InetSocketAddress(this.host,this.port);
	}
	
	@Override
	public long getStartTime() {
		return this.starttime;
	}

	protected AbstractModule(String server,String host,int port,String bean,Class<?> type){
		this.server = server;
		this.host = host;
		this.port = port;
		this.bean = bean;
		this.type = type.getName();
		this.starttime = System.currentTimeMillis();
	}
	
	public static Exporter createExporter(String server,String host,int port,String bean,Class<?> type){
		return new Exporter(server, host, port, bean, type);
	}
	
	public static Importer createImporter(String server,String host,int port,String bean,Class<?> type){
		return new Importer(server, host, port, bean, type);
	}
	
}